import playwrightApi from '../lib/playwright.js'
import { sleep } from '../util/util.js'

class DouBao {
  constructor() {
    this.page = null
    this.timeout = 5 * 60 * 1000 // 5分钟
  }

  initRoute(koa) {
    this.log('登录', 'GET http://127.0.0.1:3001/ima/login')
    this.log('对话', 'POST http://127.0.0.1:3001/ima/message')
    this.log('测试', 'GET http://127.0.0.1:3001/ima/test')

    koa.router.get('/ima/login', ctx => {
      this.chat()

      ctx.body = {
        code: 0,
        msg: 'success',
      }
    })

    koa.router.get('/ima/test', async ctx => {
      try {
        const res = await this.message('你好')

        ctx.body = {
          code: 0,
          msg: 'success',
          data: res,
        }
      } catch (e) {
        console.error(e)

        ctx.body = {
          code: 1,
          msg: e?.message || 'success',
        }
      }
    })

    koa.router.get('/ima/message', async ctx => {
      try {
        // const { body } = ctx.request
        const { query } = ctx

        if (!query.message) throw new Error('缺少消息')
        if (query.timeout != undefined) this.timeout = query.timeout

        const res = await this.message(query.message)

        ctx.body = {
          code: 0,
          msg: 'success',
          data: res,
        }
      } catch (e) {
        console.error(e)

        ctx.body = {
          code: 1,
          msg: e?.message || 'success',
        }
      }
    })
  }

  log(...args) {
    console.log('[ima]', ...args)
  }

  // 开始聊天
  async chat() {
    const { context } = playwrightApi

    if (this.page) {
      // console.log('关闭标签，重新打开')
      // await this.page.close()
      // this.page = null
    } else {
      this.page = await context.newPage()
    }

    await this.page.goto('https://ima.qq.com/')
    this.log('打开ima')
  }

  // 发送消息
  async sendMessage(message) {
    this.log('发送消息')

    const { page } = this
    await page.locator('#tagTextarea div').nth(1).fill(message)

    await sleep(3000)

    // 点击发送
    await page.locator('[viewBox="0 0 28 28"]').click()
  }

  // 判断是否启用深度思考
  async think() {
    const { page } = this

    const normal = page.locator('[data-testid="deep_think_select_button"]')
    const noNormal = page.locator('[data-testid="use-deep-thinking-switch-btn"]')

    // 正常思考
    if ((await normal.count()) > 0) {
      this.log('正常深度思考')
      const thinkBtnChecked = await normal.getAttribute('data-checked')
      return thinkBtnChecked === 'true' ? true : false
    }
    // 被禁用的情况
    else if ((await noNormal.count()) > 0) {
      this.log('被禁用的深度思考')
      const thinkBtn = await page.locator('[data-testid="use-deep-thinking-switch-btn"] button')
      const thinkBtnChecked = await thinkBtn.getAttribute('data-checked')
      return thinkBtnChecked === 'true' ? true : false
    } else {
      return false
    }
  }

  // 等待结果
  async getResult() {
    this.log('等待结果')

    const { page } = this

    // 等待跳转回答页面
    await page.waitForSelector('#HistoryScrollContainer', { timeout: this.timeout })
    this.log('跳转成功，等待回答')

    const sel = 'span:has-text("停止回答")'

    // 立即判断是否存在（不会等待）
    const exists = (await page.locator(sel).count()) > 0

    if (exists) {
      this.log('回答中...')
      await page.waitForSelector(sel, { state: 'detached', timeout: this.timeout })
    } else {
      this.log('已有回答记录，无需等待')
    }

    this.log('提取结果')

    const last = page.locator('div[data-session-id]', { timeout: this.timeout }).last()

    const markdown = last.locator('div[class^="_markdown_"]', { timeout: this.timeout }) // 匹配以 _markdown_ 开头的 class

    const content = await markdown.textContent()

    this.log('回答结果', content)

    return content
  }

  // 文本对话
  async message(message) {
    await this.chat()

    // await this.page.locator('div').filter({ hasText: /^DeepSeek V3$/ }).nth(3).click();
    // await this.page.getByText('DeepSeek V3.1').click();

    await this.sendMessage(message)
    return await this.getResult()
  }
}

export default new DouBao()
